var fs = require('fs');
var path = require('path');

module.exports = {
    exec: function (script, req, res, callback) {
        this.get(script, function (msg) {
            if (msg.result == 'fail') {
                callback(new Error(msg.result));
            } else {
                if (msg.script.endsWith(".py")) {
                    var py = require('../../modules/sys/python');
                    py.exec(req, msg.script, function (data) {
                        res.send(data);
                    });
                } else {
                    require(path.join(process.cwd(), msg.script)).fn(req, res);
                }
            }
        });
    },

    get: function (script, callback) {
        fs.exists('./service/script/' + script + '.js', function (exists) {
            if (!exists) {
                fs.exists('./service/script/' + script + '.py', function (exists) {
                    if (!exists) {
                        callback({
                            result: 'fail'
                        });
                        return;
                    }

                    callback({
                        result: 'ok',
                        script: './service/script/' + script + '.py'
                    });
                });
                return;
            }

            callback({
                result: 'ok',
                script: './service/script/' + script + '.js'
            });
        });
    }
};